import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';
import { CustomValidators } from '../../share/validators/custom-form.validators';
import { GroupService } from '../../core/services/group.service';
import { ToasterService } from '../../share/toastr/toastr.service';


@Component({
  selector: 'app-add-group',
  templateUrl: './add-group.html',
  styleUrls: ['./add-group.css'],
  providers: [BsModalService]
})
export class AddGroupComponent implements OnInit {

  public  form:       FormGroup;

  private formSubmit: boolean = false;

  groupSubscription:  Subscription;

  groupsObj:         object = {};

  groupConditions:   any[] = [];

  groupConditionSet: any[] = [];

  constructor (
    public  bsModalRef:    BsModalRef,
    private formBuilder:   FormBuilder,
    private groupService:  GroupService,
    public  toastrService: ToasterService
  ) { }


  getConditionsGroupsItems(event) {
    this.groupConditions = event;
    console.log('conditions ', this.groupConditions);

    for (let i = 0; i < this.groupConditions.length; i++) {
      if (this.groupConditions[i].id == 0) {
        this.groupConditionSet.push({
          "id":        this.groupConditions[i].id,
          "value":     this.groupConditions[i].value,
          "component": this.groupConditions[i].com
        });
      } else if (this.groupConditions[i].id == 1) {
        this.groupConditionSet.push({
          "id":        this.groupConditions[i].id,
          "value":     this.groupConditions[i].value,
          "component": this.groupConditions[i].com
        });
      } else if (this.groupConditions[i].id == 2) {
        this.groupConditionSet.push({
          "id":        this.groupConditions[i].id,
          "value":     this.groupConditions[i].value,
          "component": this.groupConditions[i].com
        });
      } else if (this.groupConditions[i].id == 3) {
        this.groupConditionSet.push({
          "id":        this.groupConditions[i].id,
          "value":     this.groupConditions[i].value,
          "component": this.groupConditions[i].com
        });
      } else if (this.groupConditions[i].id == 4) {
        this.groupConditionSet.push({
          "id":        this.groupConditions[i].id,
          "value":     this.groupConditions[i].value,
          "component": this.groupConditions[i].com
        });
      } else if (this.groupConditions[i].id == 5) {
        this.groupConditionSet.push({
          "id":        this.groupConditions[i].id,
          "value":     this.groupConditions[i].value,
          "component": this.groupConditions[i].com
        });
      }
    }
    console.log('--- conditions set ---', this.groupConditionSet, '---')
  }

  ngOnInit() {
    this.initForm();
  }

  public initForm() {
    const asin = '';

    // CustomValidators.pattern(/^B[\dA-Z]{9}|\d{9}(X|\d)$/)

    this.form = this.formBuilder.group({
      asin: ['asin', Validators.compose([Validators.minLength(10), Validators.required])]}, 
      {validator: this.validatorGroupsAsin('asin')}
      );
  }

  onSubmit() {
    const values    = this.form.value;
    const keys      = Object.keys(values)
    this.formSubmit = true;

    this.groupsObj = {
      "asin": values.asin,
      "tags": [],
      "conditions": this.groupConditionSet
    }

    if (this.form.valid) {
      this.groupService.addGroup(this.groupsObj)
          .subscribe(
            success => {
              this.toastrService.successful('Add Product Groups Successfuly ! ');
              this.bsModalRef.hide();
            },
            errors => {
              this.toastrService.errors('Add Product Groups Failed ! ');
            }
          )
    }
  }

  submit() {
    const values    = this.form.value;
    const keys      = Object.keys(values);
    this.formSubmit = true;

    this.groupsObj  = {
      "asin": values.asin,
      "tags": [],
      "conditions": this.groupConditions
    }

    if (this.form.valid) {
      this.groupSubscription = this.groupService.addGroup(this.groupsObj)
          .subscribe(
            data => {
              const errors = data.errors;
              if (errors) {
                keys.forEach(val => {
                  if (errors[val]) { this.pushError(val, errors)}
                });
                this.toastrService.successful('Add Product Group Successfuly ! ');
                this.bsModalRef.hide();
              } else {
                keys.forEach(val => {
                  const ctrl = this.form.contains[val];
                  if (!ctrl.valid) {
                    this.pushError(val, null);
                    ctrl.markAsTouched();
                  }
                });
                this.toastrService.errors('Add Product Groups Failed ! ');
              }
            }
           )
    }
  }

  private pushError(ctrl_name: string, msg: string) {
    this.form.controls[ctrl_name].setErrors({ 'msg': msg });
  }

  private validGroupsAsin(asins: string) {

    if (!asins) {
      let msg = 'Please enter ASIN !';
      console.log(msg);
      return msg;
    } else if (asins.match(/^([A-Z0-9]{10})(\s*[\s\n,]\s*([A-Z0-9]{10}))*\s*$/) === null) {
      let msg = 'ASIN format is incorrect !';
      console.log(msg);
      return msg;
    } else if (asins.split(/\s*[\s\n,]\s*/).length > 10) {
      let msg = 'Up to 10 ASINs can be imported at one time !';
      console.log(msg);
      return msg;
    }
  }

  validatorGroupsAsin(asins: string) {
    return (group: FormGroup): {[key: string]: any} => {
      const amazon_asin = group.controls[asins];
      if (!amazon_asin) {
        return {
          // asinsError: 'Please enter ASIN !'
          ASINError: true
        }
      } else if (amazon_asin.value.match(/^([A-Z0-9]{10})(\s*[\s\n,]\s*([A-Z0-9]{10}))*\s*$/) === null) {
        return {
          // asinsError: 'ASIN format is incorrect !'
          ASINError: true
        }
      } else if (amazon_asin.value.split(/\s*[\s\n,]\s*/).length > 10) {
        return {
          // asinsError: 'Up to 10 ASINs can be imported at one time !'
          ASINError: true
        }
      }
    }
  }

}
